﻿/*  
 *  IIS LogFile Analyser, Copyright (C) 2013. http://www.iis-analyser.com
 *  --
 *  This program is free software, provided "AS IS" WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
 * 
 *  File Author: Ian Quigley,    2013-02-23
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataStore;
using System.Configuration;
using System.Text;
using Web.DisplayView;
using System.Web.Services;
using Web.Filter;

namespace Web
{
    public partial class View : BasePage
    {
        protected void Page_Load( object sender, EventArgs e )
        {
            var id = QueryParamLong( "id" );
            if (id == 0)
                Response.Redirect( "ViewList.aspx" );

            var view = Data.View( id );
            if (view == null)
                Response.Redirect( "ViewList.aspx" );

            litName.Text = view.Name;
            litResult.Text = RenderView( view, null );

            litFilters.Text = FilterFactory.BuildHtmlFor( view.Filters );
            Page.Title = "View: " + view.Name;
        }

        [WebMethod]
        public static AjaxResponse Render(long id, List<FilterItem> filters)
        {
            var store = BasePage.GetDataStore();
            var view = store.View( id );
            if (view == null)
                return AjaxResponse.Fail( "Could not find view id: " + id );

            return AjaxResponse.Ok( RenderView( view, filters ) );
        }

        private static string RenderView( ViewRecord view, List<FilterItem> filters )
        {
            var store = BasePage.GetDataStore();

            IDisplayView display = ViewFactory.Create(view.DisplayView);
            
            var sql = FilterFactory.UpdateSql(filters, view.Sql);                

            return display.ToHtml( store.SQL( sql ) );
        }
    }
}